package com.yearner.reviewplan.user.data;

import com.yearner.reviewplan.common.util.RedisUtil;
import com.yearner.reviewplan.user.exceptions.SessionLockException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 校验请求是否锁定
 * @author pyg
 */
@Component
public class IdentificationSession {
    private final RedisUtil redisUtil;
    private static final int MAX_FAILED_COUNT = 5;

    public IdentificationSession(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 检查失败次数
     * @param request
     */
    public void checkFailedCount(HttpServletRequest request) {
        String ipAddr = request.getRemoteAddr();
        String sCount = Optional.ofNullable(redisUtil.getNormal(ipAddr))
                .orElse("0");

        int count = Integer.parseInt(sCount);
        if (count > MAX_FAILED_COUNT) {
            redisUtil.refreshExpireTime(ipAddr);
            throw new SessionLockException();
        }
    }

    /**
     * 给当前访问的ip添加失败次数
     * @param request
     */
    public void addFailedCount(HttpServletRequest request) {
        String ipAddr = request.getRemoteAddr();
        String sCount = Optional.ofNullable(redisUtil.getNormal(ipAddr))
                .orElse("0");
        int count = Integer.parseInt(sCount) + 1;
        redisUtil.pushNormalExpire(ipAddr, Integer.toString(count),900);
    }

    /**
     * 重置失败次数
     */
    public void resetFailedCount() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String ipAddr = request.getRemoteAddr();
        redisUtil.delete(ipAddr);
    }
}
